package com.example.configuration;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Danli {
    private  volatile static Danli danli = null;
    private Danli(){};
    private static  Lock lock = new ReentrantLock();
    public static Danli getDanli() {
        lock.lock();
        try {
            if(danli != null){
                return danli;
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            danli = new Danli();
            return danli;
        }finally {
            lock.unlock();
        }


    }
    static Danli danli1;
    static Danli danli2;
    static Danli danli3;
    public static void main(String[] args) {
        Thread t1 = new MyThread01();
        Thread t2 = new MyThread02();
        Thread t3 = new MyThread03();
        t1.start();
        t2.start();
        t3.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(danli1 == danli2);
        System.out.println(danli1 == danli3);
        System.out.println(danli2 == danli3);
        System.out.println(danli1);
        System.out.println(danli2);
        System.out.println(danli3);
    }
    static class MyThread01 extends Thread {
        @Override
        public void run() {
            danli1 = getDanli();
        }
    }
    static class MyThread03 extends Thread {
        @Override
        public void run() {
            danli3 = getDanli();
        }
    }
    static class MyThread02 extends Thread {
        @Override
        public void run() {
            danli2 = getDanli();
        }
    }
}
